package middleware

import (
	"strings"

	"gitee.com/jiebaiyou/formflow/internal/tokenutil"
	"gitee.com/jiebaiyou/formflow/pkg/response"
	"github.com/gin-gonic/gin"
)

// JwtAuthMiddleware JWT认证中间件
func JwtAuthMiddleware(secret string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头获取Authorization字段
		authHeader := c.Request.Header.Get("Authorization")
		// 分割Bearer令牌
		t := strings.Split(authHeader, " ")
		if len(t) == 2 {
			// 获取令牌部分
			authToken := t[1]
			// 验证令牌是否有效
			authorized, err := tokenutil.IsAuthorized(authToken, secret)
			if authorized {
				// 从令牌中提取用户ID
				userID, err := tokenutil.ExtractIDFromToken(authToken, secret)
				if err != nil {
					// 如果提取ID失败, 返回401未授权错误
					response.Unauthorized(c, "提取ID失败", err)
					c.Abort()
					return
				}
				// 将用户ID存入请求上下文, 供后续处理函数使用
				c.Set("x-user-id", userID)
				// 继续处理请求
				c.Next()
				return
			}
			// 如果令牌无效, 返回401未授权错误
			response.Unauthorized(c, "令牌无效", err)
			c.Abort()
			return
		}
		// 如果Authorization头格式不正确, 返回401未授权错误
		response.Unauthorized(c, "未授权", "Authorization头格式不正确")
		c.Abort()
	}
}
